package com.cn.webspider;

import com.alibaba.fastjson.JSONObject;
import com.cn.api.util.HttpRequest;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Test;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.net.URL;
import java.util.Base64;
import java.util.Date;
import java.util.Properties;

/**
 * @program: demo
 * @description: 联通活动
 * @author: yihanyuan
 * @create: 2019-07-08 14:26
 */
public class ChinaUnion implements PageProcessor {
    private Site site = Site.me().setRetryTimes(3).setSleepTime(60000);
    //发件人地址
    public static String senderAddress = "897124712@qq.com";
    //收件人地址
    public static String recipientAddress = "13870598697@139.com";
    //发件人账户名
    public static String senderAccount = "897124712@qq.com";
    //发件人账户密码
    public static String senderPassword = "efadzktzvnvabced";
    //#发送邮件
    //spring.mail.default-encoding=UTF-8
    //spring.mail.host=smtp.qq.com
    //#发送者的邮箱密码
    //#spring.mail.password=1102yuan
    //spring.mail.password=efadzktzvnvabced
    //#端口
    //spring.mail.port=25
    //#协议
    //spring.mail.protocol=smtp
    //#发送者的邮箱账号
    //spring.mail.username=897124712@qq.com

    @Override
    public void process(Page page) {
//        List<String> all = page.getHtml().xpath("//div[@id='slider']/ul[@class='sliderbox']/li").all();
//        //<li> <p> <span class="fz">156****0731</span><span class="fy">获得<span class="colo">10金币</span></span> </p>
//        //     <p> <span class="fz">176****9789</span><span class="fy">获得<span class="colo">66MB</span></span> </p>
//        //     <p> <span class="fz">156****6717</span><span class="fy">获得<span class="colo">10金币</span></span> </p> </li>
//        all.stream().forEach(e -> {
//            Html html = new Html(e);
//            List<String> all1 = html.xpath("//li/p/span[@class='fy']/span[@class='colo']/text()").all();
//            if (all != null) {
//                all1.forEach(a -> {
//                    System.out.println("--------------" + a);
//                    if (a != null && a.contains("金币")) {
//                        try {
//                            sentMail(a);
//                            return;
//                        } catch (Exception ex) {
//                            ex.printStackTrace();
//                        }
//                    }
//                });
//            }
//        });
        page.getHtml().xpath("");
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {
//        Spider.create(new ChinaUnion()).addUrl("http://m.client.10010.com/wheelswing/view/shake/share_ggk.jsp?encryptusernumber=c213cd6986c5934e776fb8c418c93e66&areaid=2e15e920e8e19a6aeb5a396a16e4b162&actime=7dd6e6462ad445746c8bf0270c4916a9&acname=3f76c4bb712f8fe0b40fabe3cf026a3e55629dc468197dfad920de46e7e4028f&acCode=664ee6e3ed7bf7fd6b5accd1bf65ca65737a86441bda7d60dd8f648c65273af3&acid=AC20190704091737")
        Spider.create(new ChinaUnion()).addUrl("https://m.client.10010.com/sma-lottery/qpactivity/qingpiindex")
                .thread(1)
                .run();
    }

    @Test
    public void te() throws Exception {
//        String e = " <li> <p> <span class=\"fz\">156****0731</span><span class=\"fy\">获得<span class=\"colo\">10金币</span></span> </p>\n" +
//                "            <p> <span class=\"fz\">176****9789</span><span class=\"fy\">获得<span class=\"colo\">66MB</span></span> </p>\n" +
//                "             <p> <span class=\"fz\">156****6717</span><span class=\"fy\">获得<span class=\"colo\">10金币</span></span> </p> </li>";
//        Html html = new Html(e);
//        html.xpath("//li/p/span[@class='fy']/span[@class='colo']/text()").all();
        //1、连接邮件服务器的参数配置
//        Properties props = new Properties();
//        //设置用户的认证方式
//        props.setProperty("mail.smtp.auth", "true");
//        //设置传输协议
//        props.setProperty("mail.transport.protocol", "smtp");
//        //设置发件人的SMTP服务器地址
//        props.setProperty("mail.smtp.host", "smtp.qq.com");
//        //2、创建定义整个应用程序所需的环境信息的 Session 对象
//        Session session = Session.getInstance(props);
//        //设置调试信息在控制台打印出来
//        session.setDebug(true);
//        //3、创建邮件的实例对象
//        Message msg = getMimeMessage(session);
//        //4、根据session对象获取邮件传输对象Transport
//        Transport transport = session.getTransport();
//        //设置发件人的账户名和密码
//        transport.connect(senderAccount, senderPassword);
//        //发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
//        transport.sendMessage(msg, msg.getAllRecipients());
//        //如果只想发送给指定的人，可以如下写法
//        //transport.sendMessage(msg, new Address[]{new InternetAddress("xxx@qq.com")});
//        //5、关闭邮件连接
//        transport.close();
    }

    public void send() {
        HttpUriRequest httpUriRequest = new HttpPost(
                "https://m.client.10010.com/sma-lottery/validation/qpImgValidation.htm");

        httpUriRequest
                .setHeader("Accept",
                        "application/json, text/javascript, */*; q=0.01");
        httpUriRequest.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpUriRequest.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpUriRequest.setHeader("Connection", "keep-alive");
        httpUriRequest.setHeader("Content-Length", "69");
        httpUriRequest.setHeader("Content-Length", "XMLHttpRequest");
        httpUriRequest.setHeader("X-Requested-With", "application/x-www-form-urlencoded; charset=UTF-8");
        // 模拟浏览器，否则CSDN服务器限制访问
        httpUriRequest
                .setHeader(
                        "User-Agent",
                        "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Mobile Safari/537.36");

//        HttpResponse response = HttpUtils.httpClient.execute(httpUriRequest);

    }

    public void sentMail(String message) throws Exception {
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", "smtp.qq.com");
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);
        //设置调试信息在控制台打印出来
        session.setDebug(true);
        //3、创建邮件的实例对象
        Message msg = getMimeMessage(session, message);
        //4、根据session对象获取邮件传输对象Transport
        Transport transport = session.getTransport();
        //设置发件人的账户名和密码
        transport.connect(senderAccount, senderPassword);
        //发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(msg, msg.getAllRecipients());
        //如果只想发送给指定的人，可以如下写法
        //transport.sendMessage(msg, new Address[]{new InternetAddress("xxx@qq.com")});
        //5、关闭邮件连接
        transport.close();
    }

    public static MimeMessage getMimeMessage(Session session, String message) throws Exception {
        //创建一封邮件的实例对象
        MimeMessage msg = new MimeMessage(session);
        //设置发件人地址
        msg.setFrom(new InternetAddress(senderAddress));
        /**
         * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
         * MimeMessage.RecipientType.TO:发送
         * MimeMessage.RecipientType.CC：抄送
         * MimeMessage.RecipientType.BCC：密送
         */
        msg.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recipientAddress));
        //设置邮件主题
        msg.setSubject("联通抽奖来车了", "UTF-8");
        //设置邮件正文
        msg.setContent(message, "text/html;charset=UTF-8");
        //设置邮件的发送时间,默认立即发送
        msg.setSentDate(new Date());

        return msg;
    }

    @Test
    public void ete() throws Exception {
        String s = HttpRequest.sendPost("https://m.client.10010.com/sma-lottery/validation/qpImgValidation.htm", "mobile=17621488778&image=0969&userid=86F4FCE182905918400F7B77F5E44AA0");
        JSONObject jsonObject = (JSONObject) JSONObject.parse(s);
        //{"data":{"assetCategory":"0","assetName":"50MB","everyDayNum":"3000","id":"qp50","level":"6","price":"50","prizeCount":"3000"},"isunicom":true,"msg":"2","status":200}
        //case 1://50MBcase 2://100MBcase 3://200MB case 4://1000MB  case 5: //20钻石  case 6: //15yuan  case 7:  //50yuan
        if ("YES".equalsIgnoreCase(jsonObject.getString("code"))) {
            String result = HttpRequest.sendPost("https://m.client.10010.com/sma-lottery/qpactivity/qpLuckdraw.htm", "mobile=" + jsonObject.getString("mobile") + "&image=0969&userid=86F4FCE182905918400F7B77F5E44AA0");
            JSONObject jsonObject1 = (JSONObject) JSONObject.parse(result);
            if ("200".equals(jsonObject1.getString("status"))) {
                String level = jsonObject1.getJSONObject("data").getString("level");
                if (Integer.valueOf(level) < 5) {
                    sentMail("转到流量了");
                } else {
                    sentMail("啥都没有");
                }
            }
        }
        //ocr.app_id=rQ0225IC
        //ocr.app_key=KCtXF7zP
        //ocr.api_url=https://api.253.com/open/tywzsb/tongyong
        //  params.put("appId",appId);
        //        params.put("appKey", appKey);
        //        params.put("detect_direction","true");
        //        //imageType为URL时，传入照片的网络URL地址, 支持jpg/png/bmp格式；
        //        //imageType为BASE64时，传入照片的base64字符编码，base64编码不包含data:image前缀，且图片大小不能大于2M
        //        params.put("image", img);
        //        params.put("imageType", "BASE64");
    }

    @Test
    public void teee() throws IOException {
        URL url = new URL("https://m.client.10010.com/sma-lottery/qpactivity/getSysManageLoginCode.htm?userid=86F4FCE182905918400F7B77F5E44AA0&code=1562821803514");
        byte[] buffer = new byte[1024];
        url.openStream().read(buffer);
        String bytes = Base64.getEncoder().encodeToString(buffer);
        String s = HttpRequest.sendJDPost("https://api.253.com/open/tywzsb/tongyong", "appId=rQ0225IC&appKey=KCtXF7zP&detect_direction=true&image=" + bytes + "&imageType=BASE64");
        System.out.println(s);
    }
}
